//
//  SignalAssistorMainTableViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 3/31/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "SignalAssistorMainTableViewController.h"

@interface SignalAssistorMainTableViewController ()

@end

@implementation SignalAssistorMainTableViewController
@synthesize sections=_sections;
@synthesize addTimerGroupSection=_addTimerGroupSection;
//@synthesize syncTimeTextField=_syncTimeTextField;
@synthesize addTimerGroupButton=_addTimerGroupButton;
@synthesize timerGroupSectionList=_timerGroupSectionList;
@synthesize timePicker=_timePicker;
@synthesize detailEditController=_detailEditController;
@synthesize allowDelete=_allowDelete;
@synthesize publicSender=_publicSender;
@synthesize timer=_timer;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_addTimerGroupSection release];
//    [_syncTimeTextField release];
    [_timerGroupSectionList release];
    [_addTimerGroupButton release];
    [_timePicker release];
    [_detailEditController release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [XMLParser loadDataXML];
    
    [super viewDidLoad];
    [self setAllowDelete:NO];
    [self setTitle:@"Timer List"];
    [[self navigationController] setNavigationBarHidden:YES animated:YES];
    if (!_timerGroupSectionList) {
        _timerGroupSectionList=[[NSMutableArray alloc] init];
    }
    if(!_addTimerGroupSection)
    {
        _addTimerGroupSection=[[TableSection alloc]init];
        _addTimerGroupSection.contents=[[[NSArray alloc] initWithObjects:@"Add a new timer group", nil] autorelease];
        _addTimerGroupSection.header=@"New Timer Group";
    }
    
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
//        NSMutableArray *sectionList=[[[NSMutableArray alloc] init] autorelease];
        [_sections addObject:_addTimerGroupSection];
        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        if (timerGroupList.count>0) {
            self.timerGroupSectionList=[[[NSMutableArray alloc] init] autorelease];
            
            for (int i=0; i<timerGroupList.count; i++) {
                TimerGroup *timerGroup=[timerGroupList objectAtIndex:i];
                
                TableSection *timerGroupSection=[[[TableSection alloc]init] autorelease];
                
                timerGroupSection.header=[[NSString stringWithString:@"Sync Time:"] stringByAppendingString:timerGroup.syncTime];
                NSArray *signalList=timerGroup.signalList;
                NSMutableArray *sectionContents=[[[NSMutableArray alloc]init]autorelease];
                [sectionContents addObject:@"Add a new signal"];
                for (int j=0; j<signalList.count; j++) {
                    Signal *signal=[signalList objectAtIndex:j];
                    NSString *content=[signal.signalName stringByAppendingFormat:@" - Cycle Length: %@",signal.cycleLength];
                    [sectionContents addObject:content];
                    
                }
                timerGroupSection.contents=sectionContents;
                [self.timerGroupSectionList addObject:timerGroupSection];
                
            }
            
        }
        [_sections addObjectsFromArray:_timerGroupSectionList];
        
    }
    NSInteger tableHeight=30;
//    if(!_addTimerGroupButton)
//    {
//        _addTimerGroupButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
////        NSInteger tableHeight=13;
//        [_addTimerGroupButton setFrame:CGRectMake(CONST_portraitIndex+CONST_portraitCellWidth*2/3,tableHeight,CONST_portraitCellWidth/3,CONST_section_header_height)];
////        [_addTimerGroupButton set
//        
////        [_addTimerGroupButton setTitle:@"Add Timer Group" forState:UIControlStateNormal];
//        [_addTimerGroupButton addTarget:self action:@selector(clickUploadProjectButton) 
//                     forControlEvents:UIControlEventTouchUpInside];
//        [_addTimerGroupButton setTitle:@"Load Projects" forState:UIControlStateNormal];
//        [self.tableView addSubview:_addTimerGroupButton];
//        [self.tableView bringSubviewToFront:_addTimerGroupButton];
//        
//        
//    }
    if(!_addTimerGroupButton)
    {
        _addTimerGroupButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_addTimerGroupButton setFrame:CGRectMake(300-80,((40-24)/2),80,24)];
        [_addTimerGroupButton setTitle:@"Remove" forState:UIControlStateNormal];
        [_addTimerGroupButton addTarget:self action:@selector(clickLoadProjectListButton) 
                         forControlEvents:UIControlEventTouchUpInside];
        
    }
//    [self.view addSubview:_addTimerGroupButton];
//    [self.view bringSubviewToFront:_addTimerGroupButton];
    
    if (!_timePicker) {
        _timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 250)];
        _timePicker.datePickerMode = UIDatePickerModeTime;
        _timePicker.hidden = YES;
        NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
        [inputFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00:00"];
        [_timePicker setDate:inputDate];
        [self.view addSubview:_timePicker];
    }

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.addTimerGroupSection=nil;
//    self.syncTimeTextField=nil;
    self.timerGroupSectionList=nil;
    self.addTimerGroupButton=nil;
    self.timePicker=nil;
    self.detailEditController=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[self navigationController] setNavigationBarHidden:YES];
    {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        //        NSMutableArray *sectionList=[[[NSMutableArray alloc] init] autorelease];
        [self.sections addObject:_addTimerGroupSection];
        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        if (timerGroupList.count>0) {
            self.timerGroupSectionList=[[[NSMutableArray alloc] init] autorelease];
            for (int i=0; i<timerGroupList.count; i++) {
                TimerGroup *timerGroup=[timerGroupList objectAtIndex:i];
                
                TableSection *timerGroupSection=[[[TableSection alloc]init] autorelease];
                timerGroupSection.header=timerGroup.syncTime;
                NSArray *signalList=timerGroup.signalList;
                NSMutableArray *sectionContents=[[[NSMutableArray alloc]init]autorelease];
                [sectionContents addObject:@"Add a new signal"];
                for (int j=0; j<signalList.count; j++) {
                    Signal *signal=[signalList objectAtIndex:j];
                    NSString *content= [signal.signalName stringByAppendingFormat:@" - Cycle Length: %@",signal.cycleLength];
                    [sectionContents addObject:content];
                    
                }
                timerGroupSection.contents=sectionContents;
                [self.timerGroupSectionList addObject:timerGroupSection];
                
            }
            
        }
        [self.sections addObjectsFromArray:_timerGroupSectionList];
    }
    [self.tableView reloadData];

}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    cell.textLabel.text=sectionContentString;
    
    
    
    
    
    switch (indexPath.section) {
        case 0:
        {
//            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
//            self.syncTimeTextField=[[[UITextField alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
//            [self.syncTimeTextField setBackgroundColor:[UIColor whiteColor]]; 
//            [self.syncTimeTextField setPlaceholder:@"username"];
//            [self.syncTimeTextField setText:sectionContentString];
//            [self.syncTimeTextField setFont:[TableSection TitleFont]];
////            [self.syncTimeTextField setTag:UserNameTextField];
//            self.syncTimeTextField.delegate=self;
//            [[cell contentView] addSubview:self.syncTimeTextField];
//            [cell setBackgroundColor:[TableSection WhiteColor]];
//            
//            return cell;
        }
            break;
            
        default:
        {
            switch (indexPath.row) {
                case 0:
                    
                    break;
                    
                default:
                {
                    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
//                    cell.editingStyle=UITableViewCellEditingStyleDelete;
                    
                }
                    break;
            }
            
        }
            break;
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    
        CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
        UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
        headerView.backgroundColor = [UIColor clearColor];
        UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
        aLabel.text =[[NSString stringWithString:@"Sync Time: "] stringByAppendingString:[[self.sections objectAtIndex:section] header]];
        aLabel.font = [UIFont boldSystemFontOfSize:16.0];
        aLabel.textAlignment = UITextAlignmentLeft;
        aLabel.backgroundColor = [UIColor clearColor];
        aLabel.textColor=[UIColor darkGrayColor];
        
//        aLabel.textColor = [UIColor whiteColor];
//        UILabel* label =[[UILabel alloc] init];
//        [label setText:[[self.sections objectAtIndex:section] header]];
//        
//        label.backgroundColor = [UIColor clearColor];
//        
////        UIImageView *titleImage = [[[UIImageView alloc] initWithImage:
////                                    [UIImage imageNamed:@"MyTitlePicture.png"]] autorelease];
////        CGRect imageViewRect = CGRectMake(0.0,  0.0, 320 , 40);
////        titleImage.frame = imageViewRect;
////        titleImage.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [headerView addSubview:aLabel];
        
        
        //Then you can add a UILabel to your headerView
        
    if (section != 0){
        UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [newbutton setFrame:CGRectMake(300-80,((40-24)/2),80,24)];
        [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
//        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        [newbutton setTag:(section-1)];
        [newbutton addTarget:self action:@selector(removeTimerGroupByID:) 
                       forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:newbutton];
    }
    return headerView;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.row!=0) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Commit the delete
        [XMLParser removeSignalByTimerGroupIDAndSignalID:[NSString stringWithFormat:@"%d",(indexPath.section-1)] signalID:[NSString stringWithFormat:@"%d", (indexPath.row-1)]];
        {
            self.sections = [[[NSMutableArray alloc] init] autorelease];
            //        NSMutableArray *sectionList=[[[NSMutableArray alloc] init] autorelease];
            [self.sections addObject:_addTimerGroupSection];
            NSArray *timerGroupList=[XMLParser getTimerGroupList];
            if (timerGroupList.count>0) {
                self.timerGroupSectionList=[[[NSMutableArray alloc] init] autorelease];
                for (int i=0; i<timerGroupList.count; i++) {
                    TimerGroup *timerGroup=[timerGroupList objectAtIndex:i];
                    
                    TableSection *timerGroupSection=[[[TableSection alloc]init] autorelease];
                    timerGroupSection.header=timerGroup.syncTime;
                    NSArray *signalList=timerGroup.signalList;
                    NSMutableArray *sectionContents=[[[NSMutableArray alloc]init]autorelease];
                    [sectionContents addObject:@"Add a new signal"];
                    for (int j=0; j<signalList.count; j++) {
                        Signal *signal=[signalList objectAtIndex:j];
                        NSString *content=[signal.signalName stringByAppendingFormat:@" - Cycle Length: %@",signal.cycleLength];
                        [sectionContents addObject:content];
                        
                    }
                    timerGroupSection.contents=sectionContents;
                    [self.timerGroupSectionList addObject:timerGroupSection];
                    
                }
                
            }
            [self.sections addObjectsFromArray:_timerGroupSectionList];
        }
        [self.tableView reloadData];
    }
}

/*
// Override to support editing the table view.
 
 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 0:
        {
            // Initialization code
           
//            _timePicker.date = [NSDate date];
//            [_timePicker addTarget:self
//                           action:@selector(selectTime:)
//                 forControlEvents:UIControlEventValueChanged];
            
            [[self navigationController] setNavigationBarHidden:NO];
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectTime:)];
            self.navigationItem.rightBarButtonItem = item;
            [item release];
            [self.editButtonItem setStyle:UIBarButtonItemStyleDone];
            [self.timePicker setHidden:NO];
            self.title=@"Select sync time";
            [_timePicker release];
        }
            break;
            
        default:
        {
            if (indexPath.row==0) {
                NSString *timerGroupIDString=[NSString stringWithFormat:@"%d",(indexPath.section-1)];
                NSArray *signalList=[XMLParser getSignalListByTimerGroupID:timerGroupIDString];
                int maxSignalID=-1;
                for (int i=0; i<signalList.count; i++) {
                    Signal *signal=[signalList objectAtIndex:i];
                    if ([signal.signalID intValue]>maxSignalID) {
                        maxSignalID=[signal.signalID intValue];
                    }
                }
                maxSignalID=maxSignalID+1;
                NSString *signalIDString=[NSString stringWithFormat:@"%d",maxSignalID];
                [_detailEditController release];
                _detailEditController=[[SignalAssistorDetailEditViewController alloc]initWithNibNameTimerGroupIDAndSignalID:@"SignalAssistorDetailEditViewController" timerGroupID:timerGroupIDString signalID:signalIDString bundle:nil] ;
                [_detailEditController setTitle:@"Detail"];
                
                [self.navigationController pushViewController:_detailEditController animated:YES];
                [self.navigationController setNavigationBarHidden:NO animated:YES];
            }else {
                NSString *timerGroupIDString=[NSString stringWithFormat:@"%d",(indexPath.section-1)];
                NSString *signalIDString=[[[XMLParser getSignalListByTimerGroupID:timerGroupIDString] objectAtIndex:(indexPath.row-1)] signalID];
               
                [_detailEditController release];
                _detailEditController=[[SignalAssistorDetailEditViewController alloc]initWithNibNameTimerGroupIDAndSignalID:@"SignalAssistorDetailEditViewController" timerGroupID:timerGroupIDString signalID:signalIDString bundle:nil] ;
                [_detailEditController setTitle:@"Detail"];
                
                [self.navigationController pushViewController:_detailEditController animated:YES];
                [self.navigationController setNavigationBarHidden:NO animated:YES];
            }
            
            
            break;
        }
            break;
    }
}
#pragma mark - TextField delegate
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
//}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        // Launch nuclear strike !
        
        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        int tag=[self.publicSender tag];
        [XMLParser removeTimerGroupByID:[[timerGroupList objectAtIndex:tag] timerGroupID]];
        [self.sections removeObjectAtIndex:tag+1];
//        {
//            self.sections = [[[NSMutableArray alloc] init] autorelease];
//            //        NSMutableArray *sectionList=[[[NSMutableArray alloc] init] autorelease];
//            [self.sections addObject:_addTimerGroupSection];
//            NSArray *timerGroupList=[XMLParser getTimerGroupList];
//            if (timerGroupList.count>0) {
//                self.timerGroupSectionList=[[[NSMutableArray alloc] init] autorelease];
//                for (int i=0; i<timerGroupList.count; i++) {
//                    TimerGroup *timerGroup=[timerGroupList objectAtIndex:i];
//                    
//                    TableSection *timerGroupSection=[[[TableSection alloc]init] autorelease];
//                    timerGroupSection.header=timerGroup.syncTime;
//                    NSArray *signalList=timerGroup.signalList;
//                    NSMutableArray *sectionContents=[[[NSMutableArray alloc]init]autorelease];
//                    [sectionContents addObject:@"Add a new signal"];
//                    for (int j=0; j<signalList.count; j++) {
//                        Signal *signal=[signalList objectAtIndex:j];
//                        NSString *content=[signal.signalName stringByAppendingFormat:@" - Cycle Length: %@",signal.cycleLength];
//                        [sectionContents addObject:content];
//                        
//                    }
//                    timerGroupSection.contents=sectionContents;
//                    [self.timerGroupSectionList addObject:timerGroupSection];
//                    
//                }
//                
//            }
//            [self.sections addObjectsFromArray:_timerGroupSectionList];
//        }
        [self.tableView reloadData];
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}

#pragma mark - Customized codes
- (void) clickAddTimerGroupButton
{
    if ([[[[self.sections objectAtIndex:0] contents]objectAtIndex:0] isEqualToString:@"Click for sync time"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Uncompleted Input" 
                                                        message:@"Please input the timer synch to add the new group." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    TableSection *newTimerGroupSection=[[[TableSection alloc] init] autorelease];
    [self.timerGroupSectionList addObject:newTimerGroupSection];
    [_sections addObject:newTimerGroupSection];
    
}

- (void) selectTime:(id) sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeStyle=NSDateFormatterShortStyle;
//	[[self.sections objectAtIndex:0] setContents:[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil]];
    TimerGroup *newTimerGroup=[[[TimerGroup alloc] init] autorelease];
    NSArray *existingTimerGroupList=[XMLParser getTimerGroupList];
    int maximumID=0;
    
    if (existingTimerGroupList.count<=0) {
        
        [newTimerGroup setTimerGroupID:@"0"];
    }else {
        
        for (int i=0; i<existingTimerGroupList.count; i++) {
            TimerGroup *existingTimerGroup=[existingTimerGroupList objectAtIndex:i];
            if ([existingTimerGroup.timerGroupID intValue]>maximumID) {
                maximumID=[existingTimerGroup.timerGroupID intValue];
            }
        }
        [newTimerGroup setTimerGroupID:[NSString stringWithFormat:@"%d", (maximumID+1)]];
        
    }
    
    [newTimerGroup setSyncTime:[df stringFromDate:self.timePicker.date]];
    NSLog(@"Saving xml data to %@...", newTimerGroup.syncTime);
    [XMLParser createTimerGroup:newTimerGroup];
    [df release];
    
    {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        //        NSMutableArray *sectionList=[[[NSMutableArray alloc] init] autorelease];
        [self.sections addObject:_addTimerGroupSection];
        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        if (timerGroupList.count>0) {
            self.timerGroupSectionList=[[[NSMutableArray alloc] init] autorelease];
            for (int i=0; i<timerGroupList.count; i++) {
                TimerGroup *timerGroup=[timerGroupList objectAtIndex:i];
                
                TableSection *timerGroupSection=[[[TableSection alloc]init] autorelease];
                timerGroupSection.header=timerGroup.syncTime;
                NSArray *signalList=timerGroup.signalList;
                NSMutableArray *sectionContents=[[[NSMutableArray alloc]init]autorelease];
                [sectionContents addObject:@"Add a new signal"];
                for (int j=0; j<signalList.count; j++) {
                    Signal *signal=[signalList objectAtIndex:j];
                    NSString *content=[signal.signalName stringByAppendingFormat:@" - Cycle Length: %@",signal.cycleLength];
                    [sectionContents addObject:content];
                    
                }
                timerGroupSection.contents=sectionContents;
                [self.timerGroupSectionList addObject:timerGroupSection];
                
            }
            
        }
        [self.sections addObjectsFromArray:_timerGroupSectionList];
    }
    
    
    
//    TableSection *newTimerGroupSection=[[TableSection alloc] init] ;
//    newTimerGroupSection.contents=[[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil] autorelease];
//    NSString *headerString=[[[[NSString alloc] initWithString:@"Timer Group - Sync Time "] autorelease] stringByAppendingString:[df stringFromDate:self.timePicker.date]] ;
//    newTimerGroupSection.header=headerString;
////    [headerString release];
//    [self.timerGroupSectionList addObject:newTimerGroupSection];
//    [_sections addObject:newTimerGroupSection];
//    [sender removeFromSuperview];
	
//    [newTimerGroupSection release];
    [self.timePicker setHidden:YES];
    self.navigationItem.rightBarButtonItem=nil;
    [[self navigationController] setNavigationBarHidden:YES];
    self.title=@"Timer List";
    NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
    [inputFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00:00"];
    [_timePicker setDate:inputDate];
    [self.tableView reloadData];
    
}


- (void) removeTimerGroupByID:(id) sender
{
    self.publicSender=sender;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the timer group?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (void) updateTimer:(id) sender {
    for (int i=0; i<self.sections.count; i++) {
        TableSection *section=[self.sections objectAtIndex:i];
        if (i==0) {
            continue;
        }
        NSString *timerGroupIDString=[NSString stringWithFormat:@"%d",i-1];
        TimerGroup *timerGroup=[XMLParser getTimerGroup:timerGroupIDString];
        for (int j=0; j<section.contents.count; j++) {
            if (j==0) {
                continue;
            }
            
            NSString *signalIDString=[[[XMLParser getSignalListByTimerGroupID:timerGroupIDString] objectAtIndex:j-1] signalID];
//            NSString *content=[section.contents objectAtIndex:j];
            Signal *signal=[timerGroup.signalList objectAtIndex:j-1];
            NSString *newContent=[[[signal signalName] stringByAppendingFormat:@" - %d/",[TrafficSignalTimer calculateCycleTimer:timerGroupIDString signalID:signalIDString]] stringByAppendingString:signal.cycleLength];
            [section.contents replaceObjectAtIndex:j withObject:newContent];
            
        }
       
        
    }
    [self.tableView reloadData];
}
@end
